package autocode

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/autocode"
	autoCodeReq "github.com/flipped-aurora/gin-vue-admin/server/model/autocode/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
	"github.com/golang-module/carbon/v2"
)

type DzxService struct {
}

// CreateDzx 创建Dzx记录
// Author [piexlmax](https://github.com/piexlmax)
func (dzxService *DzxService) CreateDzx(dzx autocode.Dzx) (err error) {
	err = global.GVA_DB.Create(&dzx).Error
	return err
}

// DeleteDzx 删除Dzx记录
// Author [piexlmax](https://github.com/piexlmax)
func (dzxService *DzxService) DeleteDzx(dzx autocode.Dzx) (err error) {
	err = global.GVA_DB.Delete(&dzx).Error
	return err
}

// DeleteDzxByIds 批量删除Dzx记录
// Author [piexlmax](https://github.com/piexlmax)
func (dzxService *DzxService) DeleteDzxByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]autocode.Dzx{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateDzx 更新Dzx记录
// Author [piexlmax](https://github.com/piexlmax)
func (dzxService *DzxService) UpdateDzx(dzx autocode.Dzx) (err error) {
	err = global.GVA_DB.Model(autocode.Dzx{}).Where("id = ?", dzx.ID).
		Update("order", dzx.Order).
		Update("mark", dzx.Mark).
		Update("remark", dzx.Remark).Error
	return err
}

// GetDzx 根据id获取Dzx记录
// Author [piexlmax](https://github.com/piexlmax)
func (dzxService *DzxService) GetDzx(id uint) (err error, dzx autocode.Dzx) {
	err = global.GVA_DB.Where("id = ?", id).First(&dzx).Error
	return
}

// GetDzxInfoList 分页获取Dzx记录
// Author [piexlmax](https://github.com/piexlmax)
func (dzxService *DzxService) GetDzxInfoList(info autoCodeReq.DzxSearch) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&autocode.Dzx{})
	if info.Card != "" {
		db.Where("card = ?", info.Card)
	}
	if info.Flag != nil {
		db.Where("flag = ?", info.Flag)
	}
	if info.Name != "" {
		db.Where("name = ?", info.Name)
	}
	if info.ModifiedOn != nil {
		cDate := carbon.Time2Carbon(*info.ModifiedOn)
		db.Where("modified_on >=? and modified_on <=? ", cDate.StartOfDay().Carbon2Time(), cDate.EndOfDay().Carbon2Time())
	}
	var dzxs []autocode.Dzx
	// 如果有条件搜索 下方会自动创建搜索语句
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Order("modified_on desc").Limit(limit).Offset(offset).Find(&dzxs).Error
	return err, dzxs, total
}
